package com.crealth.memcached;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import com.crealth.db.CdrDb;
import com.crealth.db.UserDb;
import com.crealth.model.UserModel;
import com.crealth.utils.StringUtil;

public class CdrCached {
	private static final String cdrKey = "cdr_user_id_";
	private static ConcurrentHashMap<Integer, Set<String>> userCdrCalleeMap 
		= new ConcurrentHashMap<Integer, Set<String>>();
	
	public static void initUserCdrCached() {
		String cdrTbName = "e_cdr_" + StringUtil.getCurrentDay().substring(0, 6);
		String cdrPreMonthTbName = "e_cdr_" + StringUtil.getPreMonthString(-1).substring(0, 6);

		List<UserModel> userls = UserDb.selectAllOnJobUser();
		for (UserModel user : userls) {
			int curuserID = user.getId();
			List<String> userCalleels = CdrDb.selectAllCdrCalleeByUserID(cdrTbName, curuserID);
			Set<String> userCalleeSet = new HashSet<String>(userCalleels);
			List<String> calleePrels = CdrDb.selectAllCdrCalleeByUserID(cdrPreMonthTbName, curuserID);
			for (String callee : calleePrels) {
				userCalleeSet.add(callee);
			}
			
			userCdrCalleeMap.put(curuserID, userCalleeSet);
			String key = cdrKey + curuserID;
			MemcachedMgr.cachedClient.set(key, userCalleeSet);
		}
	}	
	
	public static void addUserCdr(Integer userID, String callee) {		
		Set<String> calleeSet = getUserCdrCalleeSet(userID);
		if (calleeSet != null) {
			calleeSet.add(callee);
		}
	}
	
	public static Set<String> getUserCdrCalleeSet(Integer userID) {
		Set<String> calleeSet = null;
		if (userCdrCalleeMap.containsKey(userID)) {
			calleeSet = userCdrCalleeMap.get(userID);
			
			return calleeSet;
		}
			
		String cdrTbName = "e_cdr_" + StringUtil.getCurrentDay().substring(0, 6);
		String cdrPreMonthTbName = "e_cdr_" + StringUtil.getPreMonthString(-1).substring(0, 6);
		List<String> userCalleels = CdrDb.selectAllCdrCalleeByUserID(cdrTbName, userID);
		calleeSet = new HashSet<String>(userCalleels);
		List<String> calleePrels = CdrDb.selectAllCdrCalleeByUserID(cdrPreMonthTbName, userID);
		for (String str : calleePrels) {
			calleeSet.add(str);
		}
		
		userCdrCalleeMap.put(userID, calleeSet);		
		return calleeSet;
	}
	
}
